package com.webchat.chat.core.handler;

import com.webchat.chat.core.baseEntity.BasePersistenceEnum;
import com.webchat.chat.core.tools.PersistenceEnumConverter;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Owner on 2018/6/27.
 */
public class PersistenceEnumTypeHandler<E extends Enum<?> & BasePersistenceEnum> extends BaseTypeHandler<BasePersistenceEnum> {
    private Class<E> type;

    public PersistenceEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    /**
     * 设置参数时，该如何把 Java 类型的参数转换为对应的数据库类型
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BasePersistenceEnum parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, parameter.getCode());
    }

    /**
     * 通过字段名称获取字段数据时，如何把数据库类型转换为对应的 Java 类型
     */
    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String i = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            try {
                return PersistenceEnumConverter.codeOf(type, i);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.",
                        ex);
            }
        }
    }

    /**
     * 通过字段索引获取字段数据时，如何把数据库类型转换为对应的 Java 类型
     */
    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.getNullableResult(rs, columnIndex);
    }

    /**
     * 调用存储过程后，如何把数据库类型转换为对应的 Java 类型
     */
    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.getNullableResult(cs, columnIndex);
    }
}
